package com.example.jvmsource.config;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Description:
 *
 * @author zhouyu
 * @create 2020/11/3
 * @since 1.0.0
 */
public class TraceIdUtil {
    private static final String TRACE_ID = "traceId";

    /**
     * 设置traceId
     */
    public static void setTraceId(String suffix) {
        //如果参数为空，则设置默认traceId
        String traceId = genTraceId(suffix);
        //将traceId放到MDC中
        MDC.put(TRACE_ID, traceId);
    }

    public static void setTraceId() {
        //如果参数为空，则设置默认traceId
        String traceId = genTraceId(null);
        //将traceId放到MDC中
        MDC.put(TRACE_ID, traceId);
    }

    /**
     * 获取traceId
     */
    public static String getTraceId() {
        //获取
        String traceId = MDC.get(TRACE_ID);
        //如果traceId为空，则返回默认值
        return StringUtils.isBlank(traceId) ? "" : traceId;
    }

    /**
     * 生成traceId
     */
    public static String genTraceId(String suffix) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String datetime = fmt.format(LocalDateTime.now());
        String random = RandomStringUtils.random(6, true, true);
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer traceId = stringBuffer.append(datetime).append(":").append(random);
        if(StringUtils.isNotEmpty(suffix)){
            traceId.append(":").append(suffix);
        }
        return traceId.toString();
    }
}
